package com.example.demo.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.entity.DownloadInfo;
import com.example.demo.entity.FileInfo;
import com.example.demo.entity.UploadAddress;
import com.example.demo.entity.UploadComplete;
import com.example.demo.entity.UploadPrepare;
import com.example.demo.entity.UserInfo;
import com.example.demo.entity.UserPermission;
import com.example.demo.entity.WebOfficeResponse;
import com.example.demo.service.UserService;
import com.example.demo.service.WebOfficeEditService;
import com.example.demo.service.WebOfficePreview;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
public class WebOfficeController {
    @Autowired
    private WebOfficeEditService editService;

    @Autowired
    private WebOfficePreview previewService;

    @Autowired
    private UserService userService;

    /**
     * Helper method to log all headers from a request
     */
    private Map<String, String>  logRequestHeaders(HttpServletRequest request, String endpoint) {
        log.info("Request headers for endpoint: {}", endpoint);
        Enumeration<String> headerNames = request.getHeaderNames();
        if (headerNames != null) {
            while (headerNames.hasMoreElements()) {
                String headerName = headerNames.nextElement();
                String headerValue = request.getHeader(headerName);
                log.debug("Header: {} = {}", headerName, headerValue);

                // Process x-user-query header specifically
                if ("x-user-query".equalsIgnoreCase(headerName)) {
                    Map<String, String> queryMap = parseQueryStringToMap(headerValue);
                    log.debug("Decoded x-user-query map: {}", queryMap);
                    return queryMap;
                }
            }
        }
        return Collections.emptyMap();
    }
    /**
     * Parse query string to Map with decoded values
     */
    private Map<String, String> parseQueryStringToMap(String queryString) {
        if (queryString == null || queryString.isEmpty()) {
            return Collections.emptyMap();
        }

        Map<String, String> result = new HashMap<>();
        String[] pairs = queryString.split("&");

        for (String pair : pairs) {
            int idx = pair.indexOf("=");
            String key = idx > 0 ? pair.substring(0, idx) : pair;
            String value = idx > 0 && pair.length() > idx + 1 ? pair.substring(idx + 1) : "";

            try {
                // Decode the value
                value = URLDecoder.decode(value, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                log.error("Error decoding value: {}", value, e);
            }

            result.put(key, value);
        }

        return result;
    }
    /**
     * 获取文件信息
     */
    @GetMapping("/v3/3rd/files/{file_id}")
    public WebOfficeResponse<FileInfo> GetFileInfo(
            @PathVariable("file_id") final String fileId,
            HttpServletRequest request) {
        logRequestHeaders(request, "/v3/3rd/files/" + fileId);
        return WebOfficeResponse.ok(previewService.GetFileInfo(fileId));
    }

    /**
     * 获取下载信息
     */
    @GetMapping("/v3/3rd/files/{file_id}/download")
    public WebOfficeResponse<DownloadInfo> GetDownloadInfo(
            @PathVariable("file_id") final String fileId,
            HttpServletRequest request) {
        logRequestHeaders(request, "/v3/3rd/files/" + fileId + "/download");
        return WebOfficeResponse.ok(previewService.GetDownloadInfo(fileId));
    }

    /**
     * 获取文档用户权限
     */
    @GetMapping("/v3/3rd/files/{file_id}/permission")
    public WebOfficeResponse<UserPermission> GetUserPermission(
            @PathVariable("file_id") final String fileId,
            HttpServletRequest request) {
        Map<String, String>  m=  logRequestHeaders(request, "/v3/3rd/files/" + fileId + "/permission");
        log.info("GetUserPermission={}",m);
        String userId = m.get("user");
        return WebOfficeResponse.ok(previewService.GetUserPermission(fileId,userId));
    }

    /**
     * 三阶段保存 - 准备上传阶段
     */
    @GetMapping("/v3/3rd/files/{file_id}/upload/prepare")
    public WebOfficeResponse<UploadPrepare> uploadPrepare(
            @PathVariable("file_id") String fileId,
            HttpServletRequest request) {
        logRequestHeaders(request, "/v3/3rd/files/" + fileId + "/upload/prepare");
        return WebOfficeResponse.ok(editService.UploadPrepare(fileId));
    }

    /**
     * 三阶段保存 - 获取上传地址
     */
    @PostMapping("/v3/3rd/files/{file_id}/upload/address")
    public WebOfficeResponse<UploadAddress.Response> uploadAddress(
            @PathVariable("file_id") String fileId,
            @RequestBody UploadAddress.Request uploadRequest,
            HttpServletRequest request) {
        logRequestHeaders(request, "/v3/3rd/files/" + fileId + "/upload/address");
        uploadRequest.setFileId(fileId);
        return WebOfficeResponse.ok(editService.uploadAddress(uploadRequest));
    }

    /**
     * 三阶段保存 - 上传完成后，回调通知上传结果
     */
    @PostMapping("/v3/3rd/files/{file_id}/upload/complete")
    public WebOfficeResponse<FileInfo> uploadComplete(
            @PathVariable("file_id") String fileId,
            @RequestBody UploadComplete.Request uploadRequest,
            HttpServletRequest request) {
        logRequestHeaders(request, "/v3/3rd/files/" + fileId + "/upload/complete");
        uploadRequest.setFileId(fileId);
        return WebOfficeResponse.ok(editService.uploadComplete(uploadRequest));
    }

    /**
     * 获取用户信息
     */
    @GetMapping("/v3/3rd/users")
    public WebOfficeResponse<List<UserInfo>> getUserInfo(
            @RequestParam("user_ids") List<String> userIds,
            HttpServletRequest request) {
        Map<String, String>  m=  logRequestHeaders(request, "/v3/3rd/users");
        log.info("getUserInfo1={}",m);
        List<UserInfo> userInfo = userService.getUserInfo(userIds);
        log.info("getUserInfo2={}",userInfo);
        return WebOfficeResponse.ok(userInfo);
    }
}